package com.huanletao.proxy.jdkproxy;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * <p>
 *   权限拦截校验;
 * </p>
 *
 * @package: com.huanletao.proxy.jdkproxy
 * @Description:
 * @className: PermissionInterceptor
 * @author: @NNCSKJ ADMIN
 * @copyright: Copyright (c) 2022/6/26 12:20
 * @version: V1.0
 */
public class PermissionInterceptor implements InvocationHandler, MethodInterceptor {

    private static Logger logger = LoggerFactory.getLogger(PermissionInterceptor.class);

    private Object target;

    public PermissionInterceptor() {

    }

    public PermissionInterceptor(Object target) {
        this.target = target;
    }

    /**
     *
     * @param proxy 代理类真实对象
     * @param method 代理方法；
     * @param args 执行传递参数；
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String username = (String) args[0];
        String className = method.getDeclaringClass().getName();
        Object result = null;

        // filter for generic
        if (StringUtils.isNoneBlank(username) &&StringUtils.equals("admin",username) ){
             result = method.invoke(target,args);
        }else {
            logger.error("{},权限不足,不允许访问方法.",username);
        }
        return result;
    }

    /**
     * @param obj 为由CGLib动态生成的代理类实例
     * @param method 为上文中实体类所调用的被代理的方法引用，
     * @param args 为参数值列表，MethodProxy为生成的代理类对方法的代理引用。
     * @param proxy MethodProxy为生成的代理类对方法的代理引用。
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        String username = (String) args[0];
        Object result = null;
        if (StringUtils.isNoneBlank(username) && StringUtils.equals("admin",username) ){
            proxy.invokeSuper(obj,args);
        }else {
            logger.error("{},权限不足,不允许访问方法.",username);
        }
        return result;
    }
}
